<template>
	<view class="search-suggestions-page" @touchstart="handleCloseOverlay">
		<view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="search-bar">
				<u-icon name="arrow-left" size="20" color="#303133" @click="navigateBack"></u-icon>
				<view class="search-input-container">
					<u-icon name="search" color="#c0c4cc" size="18"></u-icon>
					<input class="search-input" type="text" v-model="keyword" placeholder="城市·景点" confirm-type="search"
						:focus="isInputFocused" @confirm="loadPosts(true)" @input="handleInputChange" clearable />
				</view>
			</view>

			<view class="header-address" v-if="homePage && Object.keys(homePage).length > 0">
				<view class="header-address-left">
					<view class="header-address-left-img">
						<image :src=" homePage.imageUrl ? homePage.imageUrl : '/static/chat/icon_xc.png'" mode="">
						</image>
					</view>
					<view class="header-address-left-content">
						<view class="header-address-left-content-top">
							{{ homePage.regionName }}
						</view>
						<view class="header-address-left-content-middle">{{provinceName }}</view>
						<view class="header-address-left-content-bottom">
							{{ homePage.remarks ? homePage.remarks : "暂无" }}
						</view>
					</view>
				</view>
				<view class="header-address-right">
					<u-icon name="arrow-right" size="20" color="#000" @click="navigateBack"></u-icon>
				</view>
			</view>
		</view>

		<scroll-view scroll-y class="content-area"
			:style="{ height: 'calc(100vh - ' + (statusBarHeight + 100) + 'px)' }" @scrolltolower="handleScrollToLower">
			<view class="content-scroll">
				<u-sticky style="top: 0">
					<view class="content-tabs">
						<view class="tabs-item-wrapper" v-for="(tabsItem, index) in tabsList" :key="index">
							<view class="tabs-item" :class="{ active: tabsItem.active }" @click="switchTab(index)">
								{{ tabsItem.name }}
							</view>
							<view class="tabs-item-active" v-if="tabsItem.active">
								<image src="/static/index/tabs-active.png" mode=""></image>
							</view>
						</view>
					</view>
				</u-sticky>

				<!-- 瀑布流 -->
				<view class="waterfall-section">
					<WaterfallPosts :left-list="leftList" :right-list="rightList"
						:active-long-press-post-id="activeLongPressPostId" @itemClick="navigateToPostDetail"
						@closeOverlay="handleCloseOverlay" @longPress="handleLongPress" @touchEnd="handleTouchEnd"
						@like="handleLikePost" />
					<u-loadmore :status="waterfallLoadStatus" />
				</view>
			</view>
		</scroll-view>

		<richPostDetail :show="showRichPostDetail" @close="showRichPostDetail = false" :postData="currentDetail" />
	</view>
</template>

<script>
	import WaterfallPosts from "@/components/index/waterfall-posts/waterfall-posts.vue";
	import {
		getHomePagePosts,
		postCancelLike,
		postClientLike,
		getExpertList,
	} from "@/request/api.js";
	export default {
		components: {
			WaterfallPosts,
		},
		data() {
			return {
				statusBarHeight: 0,
				headerHeight: 0,
				keyword: "",
				isInputFocused: false,
				scrollTop: 0, // 用于控制滚动位置
				tabsList: [{
						name: "全部",
						active: 1,
					},
					{
						name: "最新",
						active: 0,
					},
					{
						name: "美食",
						active: 0,
					},
					{
						name: "土著玩乐",
						active: 0,
					},
					{
						name: "游记",
						active: 0,
					},
				],
				leftList: [],
				rightList: [],
				waterfallPage: 1,
				waterfallPageSize: 8,
				isWaterfallLoading: false,
				waterfallLoadStatus: "loadmore",
				activeLongPressPostId: null,
				currentDetail: {},
				showRichPostDetail: false,
				homePage: {},
				queryParams: {},
			};
		},

		onLoad(options) {
			if (options.keyword) {
				this.keyword = decodeURIComponent(options.keyword);
			}
			this.loadPosts(true);
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 0;

			// 动态获取顶部固定区域高度
			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this);
				query
					.select(".fixed-header")
					.boundingClientRect((data) => {
						if (data) {
							this.headerHeight = data.height;
						}
					})
					.exec();
			});
		},
		computed: {
			provinceName() {
				if (this.homePage && this.homePage.mergerName) {
					const nameArray = this.homePage.mergerName.split(",");
					return nameArray.length > 1 ? nameArray[1] : this.homePage.mergerName;
				}
				return "";
			},
		},
		onShow() {
			// 尝试在页面显示时聚焦输入框
			setTimeout(() => {
				this.isInputFocused = true;
			}, 150);
		},
		onPullDownRefresh() {
			//如果打开的是详情弹框，下拉刷新不掉接口
			if (this.showRichPostDetail) {} else {
				this.loadPosts(true);
			}
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 500);
		},
		onBackPress(options) {
			// 优先关闭详情弹框
			if (options.from === "backbutton" && this.showRichPostDetail) {
				// 需要触发组件的关闭
				this.showRichPostDetail = false;
				return true;
			}

			return false;
		},

		methods: {
			handleScrollToLower() {
				this.loadPosts(false);
			},
			navigateBack() {
				uni.navigateBack();
			},
			handleInputChange(e) {
				// 可以在这里添加输入时的联想建议逻辑 (如果需要)
			},
			onScroll(e) {
				// 处理滚动事件，防止页面滚动
				// 可以在这里添加滚动相关的逻辑
			},
			switchTab(index) {
				// 重置所有查询参数
				this.queryParams = {
					categoryId: 0,
					isNewDesc: 0,
					queryType: 1
				};
				// 根据选中的tab设置特定参数
				switch (index) {
					case 0: // 全部
						this.queryParams.categoryId = 0;
						break;
					case 1: // 最新
						this.queryParams.isNewDesc = 3;
						break;
					case 2: // 美食
						this.queryParams.categoryId = 1;
						break;
					case 3: // 土著玩乐
						this.queryParams.categoryId = 2;
						break;
					case 4: // 游记
						this.queryParams.queryType = 22;
						break;
				}
				// 将所有 tabs 的 active 设为 false
				this.tabsList.forEach((tab) => {
					tab.active = false;
				});
				// 将当前点击的 tab 设为 active
				this.tabsList[index].active = true;
				this.loadPosts(true);
			},
			handleLongPress(postId) {
				this.activeLongPressPostId = postId;
			},
			handleCloseOverlay() {
				if (this.activeLongPressPostId !== null) {
					setTimeout(() => {
						this.activeLongPressPostId = null;
					}, 100);
				}
			},
			async loadPosts(isRefresh = false) {
				if (this.isWaterfallLoading || (!isRefresh && this.waterfallLoadStatus === "nomore")) return;
				this.isWaterfallLoading = true;
				this.waterfallLoadStatus = "loading";
				if (isRefresh) {
					this.waterfallPage = 1;
					this.leftList = [];
					this.rightList = [];
				}
				const params = {
					userId: this.$store.state.userInfo.userId,
					queryType: this.queryParams.queryType || 1,
					categoryId: this.queryParams.categoryId || 0,
					pageNum: this.waterfallPage,
					pageSize: this.waterfallPageSize,
					isNewDesc: this.queryParams.isNewDesc || 0,
					title: this.keyword,
				};
				console.log("即将发送 getPosts 请求，参数为:", params);
				try {
					const res = await getHomePagePosts(params);
					if (res.data && res.data.code === 200) {
						this.homePage = res.data.homePage;
						const formattedPosts = (res.data.rows || []).map(this.formatApiData);
						this.distributePostsToColumns(formattedPosts);
						const hasMore = formattedPosts.length === this.waterfallPageSize;
						this.waterfallLoadStatus = hasMore ? "loadmore" : "nomore";
						if (hasMore) this.waterfallPage++;
					} else {
						this.waterfallLoadStatus = "loadmore";
					}
				} catch (error) {
					this.waterfallLoadStatus = "loadmore";
				} finally {
					this.isWaterfallLoading = false;
				}
			},
			distributePostsToColumns(newPosts) {
				newPosts.forEach((post) => {
					if (this.leftList.length <= this.rightList.length)
						this.leftList.push(post);
					else this.rightList.push(post);
				});
			},
			formatApiData(item) {
				const coverImage =
					item.files && item.files.length > 0 && item.files[0].fileUrl ?
					item.files[0].fileUrl.startsWith("http") ?
					item.files[0].fileUrl :
					config.cdnURL + item.files[0].fileUrl :
					"";
				const authorAvatar = item.avatar ?
					item.avatar.startsWith("http") ?
					item.avatar :
					config.cdnURL + item.avatar :
					"/static/demo/avatar_default.png";
				return {
					id: item.id,
					image: coverImage,
					content: item.content,
					author: {
						avatar: authorAvatar,
						name: item.nickName || "匿名用户",
						tag: Math.random() > 0.6 ? "高级土著" : "",
					},
					isLiked: item.isLiked,
					likeCount: item.likeCount,
					longPressTip: item.whisper || "尚未添加悄悄话",
					...item,
				};
			},
			handleTouchEnd() {},
			handleLikePost(item) {
				const isLiked = item.isLiked;
				const api = isLiked ? postCancelLike : postClientLike;

				// UI即时反馈
				item.isLiked = !isLiked;
				item.likeCount += isLiked ? -1 : 1;

				api({
					postId: item.id,
					userId: this.$store.state.userInfo.userId,
				}).catch(() => {
					// 失败时回滚
					item.isLiked = isLiked;
					item.likeCount += isLiked ? 1 : -1;
				});
			},
			navigateToPostDetail(item) {
				this.currentDetail = item;
				this.showRichPostDetail = true;
			},
		},
	};
</script>

<style lang="scss" scoped>
	page {
		background-color: rgba(255, 243, 213, 1);
		height: 100vh;
		overflow: hidden;
		/* 禁止页面滚动 */
	}

	.search-suggestions-page {
		display: flex;
		flex-direction: column;
		height: 100vh;
		overflow: hidden;
		/* 禁止页面滚动 */
	}

	.fixed-header {
		flex-shrink: 0;
		/* 防止头部被压缩 */
		background-color: rgba(255, 243, 213, 1);
		/* 移除 position: fixed，使用 flex 布局 */

		.search-bar {
			display: flex;
			align-items: center;
			height: 44px;
			padding: 0 24rpx;

			.search-input-container {
				flex: 1;
				display: flex;
				align-items: center;
				background-color: #fff;
				border-radius: 30rpx;
				height: 64rpx;
				padding: 0 20rpx;
				margin: 0 20rpx;

				.search-input {
					flex: 1;
					font-size: 28rpx;
					color: #303133;
					margin-left: 10rpx;
					height: 100%;
				}
			}
		}

		.header-address {
			display: flex;
			justify-content: space-between;
			margin: 30rpx;
			background-color: #ffffff;
			padding: 30rpx 18rpx;
			border-radius: 20rpx;

			.header-address-left {
				display: flex;

				.header-address-left-img {
					width: 200rpx;
					height: 200rpx;

					image {
						border-radius: 50%;
						width: 100%;
						height: 100%;
					}
				}

				.header-address-left-content {
					margin-left: 20rpx;

					.header-address-left-content-top {
						margin-top: 36rpx;
						font-size: 36rpx;
						font-weight: 400;
						line-height: 36rpx;
					}

					.header-address-left-content-middle {
						margin-top: 20rpx;
						color: rgba(254, 113, 49, 1);
						font-size: 26rpx;
						line-height: 26rpx;
					}

					.header-address-left-content-bottom {
						margin-top: 20rpx;
						color: rgba(77, 77, 86, 1);
						font-size: 26rpx;
						line-height: 26rpx;
					}
				}
			}

			.header-address-right {
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}

	.content-area {
		flex: 1;
		overflow: hidden;
		background-color: #fff;
		border-top-left-radius: 30rpx;
		border-top-right-radius: 30rpx;
		min-height: 100%;
	}

	.content-scroll {
		padding-bottom: calc(130rpx + env(safe-area-inset-bottom, 0px));

		.content-tabs {
			padding: 20rpx 30rpx;
			display: flex;
			position: relative;
			/* 添加滚动功能，当内容超出容器宽度时可以横向滚动 */
			overflow-x: auto;
			background-color: #fff;

			/* 隐藏滚动条 */
			&::-webkit-scrollbar {
				display: none;
			}

			.tabs-item-wrapper {
				position: relative;
				flex-shrink: 0;
				margin-right: 50rpx;
				z-index: 1;

				&:last-child {
					margin-right: 0;
				}
			}

			.tabs-item {
				padding: 10rpx 0;
				font-size: 28rpx;
				white-space: nowrap;
				color: rgba(77, 77, 86, 1);
				position: relative;
				z-index: 2;

				&.active {
					font-weight: bold;
				}
			}

			.tabs-item-active {
				position: absolute;
				top: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 50rpx;
				height: 50rpx;
				z-index: 0;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}

		.waterfall-section {
			padding: 0 10rpx;
			padding-bottom: 200rpx;
		}
	}
</style>